package com.sinven.service;

import com.sinven.common.ActionResult;
import com.sinven.common.Pager;
import com.sinven.mapper.EnviromentMapper;
import com.sinven.pojo.Environment;
import com.sinven.util.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class EnvServiceImpl implements EnvService {
    @Autowired
    private EnviromentMapper envMapper;
    @Override
    public ActionResult<List<Environment>> queryCurPageData(Integer curPage, Integer pageSize) {
        long totalRecords = envMapper.countEnviroment();
        if(totalRecords == 0 ){
            return ResultUtil.success(null);
        }
        if(pageSize == null || pageSize <0 ){
            pageSize = 5;
        }
        //给curPage赋值
        if(curPage == null || curPage<0){
            curPage = 1;
        }
        //计算总页数
        long totalPage = totalRecords % pageSize == 0?
                totalRecords / pageSize :
                totalRecords / pageSize +1;
        //防止页面恶意传值 超出部分直接显示为最后一页
        if(curPage > totalPage){
            curPage = (int)totalPage;
        }
        long startIndex = (curPage - 1) * pageSize;
        List<Environment> envList = envMapper.queryAll(startIndex, pageSize);
        return ResultUtil.success(totalRecords,envList);
    }

    @Override
    public Environment getEnvById(long eid) {
        return envMapper.queryEnvById(eid);
    }

    @Override
    public boolean addEnv(Environment env) {
        return envMapper.addEnv(env)>0;
    }

    @Override
    public boolean updateEnv(Environment env) {
        return envMapper.updateEnv(env)>0;
    }

    @Override
    public boolean deleteEnv(long eid) {
        return envMapper.deleteEnv(eid)>0;
    }

    @Override
    public Pager<Environment> queryPageData(Long curPage, Integer pageSize) {
        long totalRecords = envMapper.countEnviroment();
        if(totalRecords<=0){
            return null;
        }
        Pager<Environment> pager = new Pager<>(totalRecords,curPage,pageSize);
        List<Environment> environments = envMapper.queryAll(pager.getStartIndex(), pager.getPageSize());
        pager.setDatas(environments);
        return pager;
    }

}
